package cn.zians.controller;


import com.alibaba.fastjson.JSONObject;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.Set;


@Controller
public class SMSVerificationController {
    /**
     * 随机数串函数
     *
     * @param length
     * @return
     */
    public String randomcode(int length) {
        length = length == 0 ? 6 : length;
        char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        String result = "";
        for (int i = 0; i < length; i++) {
            int index = (int) Math.ceil(Math.random() * 9);
            result += chars[index];
        }
        System.out.println("result:" + result);
        return result;
    }

    /**
     * 短信验证码发送接口
     *
     * @param phone
     * @param model
     * @return
     */
    @RequestMapping(value = "/sendSMSCode", method = RequestMethod.POST)
    public String sendSMSCode(String phone, Model model) {
        System.out.println(phone);
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = "8a216da871bf71a10171fda1aa431753";
        String accountToken = "a3ebf42badf94d5ab04e958c1469244e";
        //请使用管理控制台中已创建应用的APPID
        String appId = "8a216da871bf71a10171fda1aa9e1759";
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone;
        String templateId = "1";
        String code = randomcode(6);
        String[] datas = {code};
        HashMap<String, Object> result = sdk.sendTemplateSMS(to, templateId, datas);
        JSONObject json = new JSONObject();
        if ("000000".equals(result.get("statusCode"))) {
            //正常返回输出data包体信息（map）
            String SMS = null;
            HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for (String key : keySet) {
                Object object = data.get(key);
                System.out.println(key + " = " + object);
            }
            json.put("success", 200);
            json.put("SMS", code);
        } else {
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg"));
            json.put("error", 1);
            json.put("msg", "短信验证码发送失败");
        }
        model.addAttribute("code", json);
        return "list";
    }


}

